﻿namespace Triad.Controls
{
    using System.Security.Permissions;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [SupportsEventValidation]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [ToolboxData(@"<{0}:tfTalk runat=server></{0}:tfTalk>")]
    public partial class tfTalk : WebControl, ICallbackEventHandler
    {

        private bool IsDesignTime
        {
            get { return Site != null && Site.DesignMode; }
        }

        /// <summary>
        /// Renders the design time code.
        /// </summary>
        /// <param name="writer">The writer.</param>
        private static void RenderDesignTimeCode(HtmlTextWriter writer)
        {
            writer.RenderBeginTag("DIV");
            writer.Write("EDTalk");
            writer.RenderEndTag();

        }

        /// <summary>
        /// Outputs server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter"/> object and stores tracing information about the control if tracing is enabled.
        /// </summary>
        /// <param name="writer">The System.Web.UI.HTmlTextWriter object that receives the control content.</param>
        /// <remarks>
        /// Author: tim.fischer,   8/25/2008 - 1:41 PM
        /// Modified By:
        /// </remarks>
        public override void RenderControl(HtmlTextWriter writer)
        {
            if (IsDesignTime)
            {
                RenderDesignTimeCode(writer);
                return;
            }

            EnsureChildControls();
            RenderBeginTag(writer);
            RenderChildren(writer);
            RenderEndTag(writer);
        }

        private string RegisterScript()
        {
            ClientScriptManager cm = Page.ClientScript;
            string cbReference1 = cm.GetCallbackEventReference(this, "message", "processTTSResult", "sender", "processTTSError", false);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("TalkToServer=function(message, sender){");
            sb.AppendLine("theForm['__EVENTTARGET'].value = sender;__theFormPostData = '';__theFormPostCollection = [];WebForm_InitCallback();" + cbReference1 + ";};");

            string s = "processTTSError=function(returnmessage, sender){" +
                       "eval(returnmessage);};";
            sb.AppendLine(s);
            s = "processTTSResult=function(returnmessage, sender){" +
                "eval(returnmessage);};";
            sb.AppendLine(s);
            //s = "ProcessUIUpdates=function(obj) { var uiUpdates = eval(obj); if (uiUpdates != undefined) { for (var i = 0; i < uiUpdates.uiUpdate.length; i++) { if (uiUpdates.uiUpdate[i].iserror) { ShowError(uiUpdates.uiUpdate[i].errmsg,1); } if (uiUpdates.uiUpdate[i].key.length > 0) { elemStatus(uiUpdates.uiUpdate[i].key, !uiUpdates.uiUpdate[i].enabled); } if (uiUpdates.uiUpdate[i].ischanged) { _gE(uiUpdates.uiUpdate[i].key).value = uiUpdates.uiUpdate[i].value; } if (uiUpdates.uiUpdate[i].elem.length > 0) { _gE(uiUpdates.uiUpdate[i].elem).focus(); } if (uiUpdates.uiUpdate[i].pagecall.length > 0) { top.openModalDialog(uiUpdates.uiUpdate[i].pagecall); } } } };";
            s = "ProcessUIUpdates=function(obj) { var uiUpdates = eval(obj); if (uiUpdates != undefined) { for (var i = 0; i < uiUpdates.uiUpdate.length; i++) { if (uiUpdates.uiUpdate[i].iserror) { ShowError(uiUpdates.uiUpdate[i].errmsg,1); } if (uiUpdates.uiUpdate[i].key.length > 0) { elemStatus(uiUpdates.uiUpdate[i].key, !uiUpdates.uiUpdate[i].enabled); } if (uiUpdates.uiUpdate[i].ischanged) { _gE(uiUpdates.uiUpdate[i].key).value = uiUpdates.uiUpdate[i].value; } if (uiUpdates.uiUpdate[i].elem.length > 0) { _gE(uiUpdates.uiUpdate[i].elem).focus(); } if (uiUpdates.uiUpdate[i].fn.length > 0) { var s=unescape(uiUpdates.uiUpdate[i].fn);eval(s); } } } };";
            sb.AppendLine(s);
            return sb.ToString();
        }

        /// <summary>
        /// Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers.
        /// </summary>
        /// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream to render HTML content on the client.</param>
        /// <remarks>
        /// Author: tim.fischer,   8/25/2008 - 1:41 PM
        /// Modified By: 
        /// </remarks>
        public override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.WriteLine("</div><script type='text/javascript'>//<![CDATA[");
            writer.WriteLine(RegisterScript());
            writer.WriteLine("//]]></script>");
        }
        /// <summary>
        /// Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers.
        /// </summary>
        /// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream to render HTML content on the client.</param>
        /// <remarks>
        /// Author: tim.fischer,   8/25/2008 - 1:41 PM
        /// Modified By: 
        /// </remarks>
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.Write("<div id=\"{0}\">", ID);
        }
        #region ICallbackEventHandler Members

        private string _returnMessage;

        public string GetCallbackResult()
        {
            return _returnMessage;
        }

        public void RaiseCallbackEvent(string message)
        {
            string sender = Page.Request.Params.Get("__EVENTTARGET");
            var eventArgs = new tCallServerEventArgs(message, sender, _returnMessage) {Message = message};
            OnCallServer(eventArgs);
            _returnMessage = eventArgs.ReturnMessage;
        }

        #endregion
    }
}
